package com.yjd.pub.funds.service;

import com.yjd.comm.bank.model.BankModel;
import com.yjd.comm.bank.service.IBankService;
import com.yjd.comm.base.dao.IBaseDao;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.service.impl.BaseServiceImpl;
import com.yjd.comm.funds.dto.QuickPayDTO;
import com.yjd.comm.funds.dto.RechOrderDTO;
import com.yjd.comm.funds.enums.PayChannelEnum;
import com.yjd.comm.funds.enums.RechSourceEnum;
import com.yjd.comm.funds.enums.RechStatusEnum;
import com.yjd.comm.funds.model.RechargeOrderModel;
import com.yjd.comm.funds.service.IFundsService;
import com.yjd.comm.funds.service.IRechargeOrderService;
import com.yjd.comm.user.model.UserModel;
import com.yjd.comm.user.service.IUserService;
import com.yjd.comm.util.ArithUtil;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.NumberUtil;
import com.yjd.comm.util.QuickPayUtils;
import com.yjd.pub.funds.dao.IRechargeOrderDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <b>description</b>：充值订单表业务实现<br>
 * <b>time</b>：2017-09-19 15:40:05 <br>
 * <b>author</b>：  carl
 */
@Service("rechargeOrderService")
public class RechargeOrderServiceImpl extends BaseServiceImpl implements IRechargeOrderService {

	/**
	 * 插入
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	public RechargeOrderModel insert(RechargeOrderModel model) throws Exception {
		return this.rechargeOrderDao.insertModel(model, true);
	}

	/**
	 * 更新
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	public int update(RechargeOrderModel model) throws Exception {
		return this.rechargeOrderDao.updateModel(model, true);
	}

	/**
	 * 根据id删除
	 * 
	 * @param order_id
	 * @return
	 * @throws Exception
	 */
	public int delete(long order_id) throws Exception {
		Map<Object, Object> paramMap = new HashMap<Object, Object>();
		paramMap.put("order_id", order_id);
		return this.rechargeOrderDao.deleteModel(paramMap, true);
	}


	/**
	 * 充值生成订单
	 * @param rechargeOrder
	 * @return
	 * @throws Exception
	 */
	@Override
	public QuickPayDTO rech(RechOrderDTO rechargeOrder) throws Exception {
		if (rechargeOrder == null) {
			FrameUtil.throwBaseException1("参数有误");
		} else if (rechargeOrder.getUser_id() == null) {
			logger.error("用户id不能为空");
			FrameUtil.throwBaseException1("用户id不能为空");
		}
		RechargeOrderModel dbOrder = new RechargeOrderModel();
		BeanUtils.copyProperties(rechargeOrder, dbOrder);
		dbOrder.setStatus(RechStatusEnum.ready.getCode()); // 状态为待充值
		dbOrder.setFee(0.00);
		dbOrder.setCreate_time(FrameUtil.getTime());
		dbOrder = rechargeOrderDao.insertModel(dbOrder, true);

		BankModel bankModel = bankService.getModelById(dbOrder.getUser_id(), DbWREnums.WRITE);
		if (bankModel == null) {
			FrameUtil.throwBaseException1("用户信息异常");
		}

		UserModel userModel = userService.getModelById(dbOrder.getUser_id(), DbWREnums.WRITE);
		if(userModel==null){
			FrameUtil.throwBaseException1("用户信息不存在！");
		}
		rechargeOrder.setUsername(bankModel.getId_name());
		rechargeOrder.setBank_code(bankModel.getBank_code());
		rechargeOrder.setRegDate(userModel.getRegistration_time().toString());
		rechargeOrder.setMemo("账户(" + bankModel.getId_name() + ")充值");

		return QuickPayUtils.generateOrder(rechargeOrder, dbOrder);
	}

	/**
	 * 充值 回调
	 *
	 * @param quickPayDTO
	 * @throws Exception
	 */
	@Override
	public void callBack(QuickPayDTO quickPayDTO) throws Exception {
		if (quickPayDTO == null|| StringUtils.isBlank(quickPayDTO.getOrderAmount())|| StringUtils.isBlank(quickPayDTO.getStatus())) {
			FrameUtil.throwBaseException1("参数异常");
		}

		String factMoney = quickPayDTO.getOrderAmount();
		// 订单状态
		String status = quickPayDTO.getStatus();
		// 订单状态转为本系统状态
		RechStatusEnum rechStatusEnum = "100".equals(status)? RechStatusEnum.success: RechStatusEnum.failed;
		if (!RechStatusEnum.success.equals(rechStatusEnum)) {
            FrameUtil.throwBaseException1("当前订单为非法请求！");
		}
		Long sysid = Long.valueOf(quickPayDTO.getSysOrderId());
		RechargeOrderModel oModel = rechargeOrderDao.getModelById(sysid,true);
		if (oModel == null) {
			FrameUtil.throwBaseException1("订单不存在!");
		}
		if (oModel.getStatus() == RechStatusEnum.success.getCode()) {
			//订单状态已经成功则直接返回
			return ;
		}
		// 金额比较
		double amount = ArithUtil.round(oModel.getPrice(), 2);
		if (factMoney.compareTo(NumberUtil.formatNumber(amount, NumberUtil.FORMAT_3)) != 0) {
			FrameUtil.throwBaseException1("充值金额和订单金额不相等");
		}

		long currTime = FrameUtil.getTime();

		//更新用户资金
		fundsService.rechAddPrice(oModel,currTime);

		//更新订单状态
		Map updataMap = new HashMap();
		updataMap.put("order_id",oModel.getOrder_id());
		updataMap.put("status",rechStatusEnum.getCode());
		updataMap.put("where_status", RechStatusEnum.ready.getCode());
		Long transtime = Long.valueOf(quickPayDTO.getFinishTime());//第三方支付接收时间
		updataMap.put("finish_time",transtime);
		updataMap.put("callback_time",currTime);
		updataMap.put("trade_id",quickPayDTO.getTransId());
		PayChannelEnum payChannel = PayChannelEnum.parse(quickPayDTO.getChannel());
		if (payChannel == null) {
			FrameUtil.throwBaseException1("参数异常,无法识别的充值渠道:"+ quickPayDTO.getChannel());
		}
		updataMap.put("channel",payChannel.getChannel());
		if(rechargeOrderDao.updateByMap(updataMap,true)!=1){
			FrameUtil.throwBaseException1("更新充值订单表失败");
		}
	}

	@Override
	public Double querySumPayPrice(Long startTime, Long endTime) throws Exception {
           if(startTime==null||endTime==null){
           	 FrameUtil.throwBaseException1("请求参数不能为空");
		   }
		return rechargeOrderDao.querySumPayPrice(FrameUtil.newHashMap("startTime",startTime,"endTime",endTime));
	}


	@Override
	public void adminRechargeAoumnt(RechargeOrderModel orderModel) throws Exception {
		if(orderModel==null){
			FrameUtil.throwBaseException1("请求参数不能为空");
		}

		if(orderModel.getUser_id()==null){
			FrameUtil.throwBaseException1("充值的用户不能为空");
		}

		UserModel userModel = userService.getModelById(orderModel.getUser_id(),DbWREnums.READ);
		if(userModel==null){
			FrameUtil.throwBaseException1("充值的用户不存在");
		}

		if(orderModel.getPrice()==null){
			FrameUtil.throwBaseException1("充值金额不正确");
		}
		Long currtime  =  FrameUtil.getTime();
		orderModel.setOrder_source(RechSourceEnum.BACK.getCode());
		orderModel.setCreate_time(currtime);
		orderModel.setStatus(RechStatusEnum.success.getCode());

		orderModel = rechargeOrderDao.insertModel(orderModel,true);

		//更新用户资金
		fundsService.rechAddPrice(orderModel,currtime);
	}

	@Resource
	private IRechargeOrderDao rechargeOrderDao;
	@Resource
	private IBankService bankService;

	@Resource
	private IFundsService fundsService;

	@Resource
	private IUserService userService;

	@Override
	public IBaseDao getBaseDao() {
		return this.rechargeOrderDao;
	}

}
